﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Xml.Serialization;

namespace OverlakeServer_SOAP
{
    /// <summary>
    /// A helper class that manages the calendar.
    /// </summary>
    static class CalendarFactory
    {
        private static readonly List<SharedData.CalendarEvent> CalendarItemCache = new List<SharedData.CalendarEvent>();
        private static bool _calendarLock = false;

        static CalendarFactory()
        {
            LoadCalendar();

            new Thread(() =>
                {
                    while (true)
                    {
                        while (_calendarLock) ;
                        _calendarLock = true;

                        CalendarItemCache.RemoveAll(m => m.StartTime > DateTime.Now);

                        LoadCalendar();
                        _calendarLock = false;

                        Thread.Sleep(60 * 10 * 1000);
                    }
                }).Start();
        }

        public static void LoadCalendar()
        {
            WebRequest request = WebRequest.Create(@"http://overlake.tandemcal.com/index.php?type=export&action=xml&limit=10000");
            var response = request.GetResponse();

            var ser = new XmlSerializer(typeof(Calendar.tfs_events));
            var v = (Calendar.tfs_events)ser.Deserialize(response.GetResponseStream());

            var events = from ev in v.@event
                         let ci = new SharedData.CalendarEvent
                                      {
                                          Description = ev.description,
                                          EndTime = DateTime.Parse(ev.time_end),
                                          StartTime = DateTime.Parse(ev.time_start),
                                          id = int.Parse(ev.id),
                                          LastModified = DateTime.Parse(ev.last_modified),
                                          Link = ev.link,
                                          Name = ev.name,
                                          IsLetterDay = ev.name.StartsWith("Day "),
                                          TBD = ev.tbd_start == "t"
                                      }
                         select ci;

            events = from e in events
                     where CalendarItemCache.All(c => c.id != e.id)
                     select e;

            CalendarItemCache.AddRange(events);
        }

        public static List<SharedData.CalendarEvent> GetFilteredCalendarItems(DateTime start, DateTime end)
        {
            return (from c in CalendarItemCache
                    where c.StartTime > start
                    where c.StartTime < end
                    select c).ToList();
        }
    }
}